package ui;

import config.GameConfig;
import config.LayerConfig;
import controller.GameController;
import controller.PlayerController;
import dto.GameDto;

import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.List;

/**
 * Created by je on 2015/7/4.
 */
public class JPanelGame extends JPanel {

    private List<Layer> layers  ;

    private GameDto dto ;

    public JPanelGame(GameDto dto) {
        this.dto = dto ;
        initLayer();
    }

    public void setGameController(PlayerController controller){
        this.addKeyListener(controller);
    }


    private void initLayer() {
        GameConfig gameConfig = GameConfig.getInstance();
        List<LayerConfig> layerConfigs = gameConfig.getLayerConfigs();
        Layer layer ;
        layers = new ArrayList<Layer>(layerConfigs.size());
        for (LayerConfig config : layerConfigs) {
            try {
                Class<?> aClass = Class.forName(config.getClassName());
                Constructor<?> constructor = aClass.getConstructor(int.class, int.class, int.class, int.class);
                layer = (Layer) constructor.newInstance(config.getX(), config.getY(), config.getW(), config.getH());
                layer.setDto(dto);
                layers.add(layer);
            } catch (Exception e) {
                throw new RuntimeException("根据配置实例化窗口出错",e);
            }
        }

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        for (Layer layer : layers) {
            layer.paint(g);
        }
        this.requestFocus();
    }

}












